package algorithmlearn.sort;

import javafx.util.Pair;

import java.util.PriorityQueue;
import java.util.function.Consumer;

//对有序列表 归并排序
public class MergeOrderList {

    public static void main(String[] args) {
        int[] a1 = {1, 2, 3, 4, 5, 6, 7, 8};
        int[] a2 = {2, 4, 5, 9, 17, 28};
        int[] a3 = {1, 3, 5, 14, 16, 18, 38};

        mergeSort(System.out::println, a1, a2, a3);
    }


    private static void mergeSort(Consumer<Item> consumer, int[]... arrays) {
        PriorityQueue<Item> priorityQueue = new PriorityQueue<>(arrays.length);
        for (int i = 0; i < arrays.length; i++) {
            if (arrays[i].length == 0) {
                continue;
            }
            priorityQueue.offer(new Item(i, 0, arrays[i][0]));
        }
        while (!priorityQueue.isEmpty()) {
            Item poll = priorityQueue.poll();
            consumer.accept(poll);
            int[] valueArray = arrays[poll.arraysIndex];
            Integer index = poll.index;
            if (index != valueArray.length - 1) {
                int next = index + 1;
                priorityQueue.offer(new Item(poll.arraysIndex, next, valueArray[next]));
            }
        }
    }
}

class Item implements Comparable<Item> {

    public Integer arraysIndex;
    public Integer index;
    public Integer value;

    public Item(Integer arraysIndex, Integer index, Integer value) {
        this.arraysIndex = arraysIndex;
        this.index = index;
        this.value = value;
    }

    @Override
    public String toString() {
        return "[" + this.value + "] ===>>> 第[" + this.arraysIndex + 1 + "]个数组,第[" + this.index + 1 + "]个元素";
    }

    @Override
    public int compareTo(Item o) {
        return this.value.compareTo(o.value);
    }
}
